<template>
  <el-dialog :title="dialogTitle" :visible.sync="visible" width="1200px" append-to-body :close-on-click-modal="false"
    @close="handleClose">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading :text="`加载中...`" fullscreen></el-loading>
    </div>

    <el-form ref="form" :model="dialogForm" :rules="rules" label-width="100px" v-else>
      <!-- 第一行：咨询号、姓名、手机号 -->
      <el-row :gutter="15" class="mb8">
        <el-col :span="8">
          <el-form-item label="咨询号" prop="travelConsult.consultNumber">
            <el-input v-model="dialogForm.travelConsult.consultNumber" readonly style="width: 260px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="姓名" prop="travelClient.clientName">
            <el-input v-model="dialogForm.travelClient.clientName" disabled style="width: 260px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号" prop="travelClient.clientTel">
            <el-input v-model="dialogForm.travelClient.clientTel" disabled style="width: 260px;" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：出行人数、意向目的地、预算 -->
      <el-row :gutter="15" class="mb8">
        <el-col :span="8">
          <el-form-item label="出行人数" prop="travelConsult.travelerCount">
            <el-input v-model="dialogForm.travelConsult.travelerCount" disabled style="width: 260px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="意向目的地" prop="travelConsult.preferredDestination">
            <el-input v-model="dialogForm.travelConsult.preferredDestination" disabled style="width: 260px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预算" prop="travelConsult.budget">
            <el-input v-model="dialogForm.travelConsult.budget" disabled style="width: 260px;" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：预计出发时间、可调整时间、出行天数 -->
      <el-row :gutter="15" class="mb8">
        <el-col :span="8">
          <el-form-item label="预计出发时间" prop="travelConsult.estimatedTime">
            <el-input v-model="dialogForm.travelConsult.estimatedTime" disabled style="width: 260px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="可调整时间" prop="travelConsult.flexibleDays">
            <el-input v-model="dialogForm.travelConsult.flexibleDays" disabled style="width: 260px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出行天数" prop="travelConsult.plannedDays">
            <el-input v-model="dialogForm.travelConsult.plannedDays" disabled style="width: 260px;" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 备注信息 -->
      <el-row class="mb8">
        <el-col :span="24">
          <el-form-item label="备注信息" prop="travelConsult.remark">
            <el-input v-model="dialogForm.travelConsult.remark" type="textarea" rows="3" disabled
              style="width: 1048px;" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 费用区域 -->
      <div class="total-fee-container">
        <hr style="margin-bottom: 30px;">
        <el-row :gutter="15" class="mb8">
          <el-col :span="8" style="margin-left: 40px;">
            <el-form-item label="旅行费用合计">
              <el-input v-model="dialogForm.travelMoneyTotal" readonly style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="服务费用合计">
              <el-input v-model="dialogForm.serviceMoneyTotal" readonly style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="费用总计">
              <el-input v-model="dialogForm.moneyTotal" readonly style="font-weight: bold;width: 200px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <hr>
      </div>

      <!-- 行程内容列表（核心：确保数据加载后渲染） -->
      <div class="dynamic-schedule-content">
        <!-- 无数据时显示提示 -->
        <div v-if="dialogForm.scheduleContents.length === 0" class="no-content">
          暂无行程内容
        </div>

        <!-- 有数据时循环渲染 -->
        <div v-for="(content, index) in dialogForm.scheduleContents" :key="content.scheduleContentId || index"
          class="step-content">
          <div style="display: flex; justify-content: space-between;">
            <h3>行程内容 {{ index + 1 }}</h3>
          </div>

          <el-row :gutter="15" class="mb8">
            <el-col :span="12">
              <el-form-item label="开始时间">
                <el-input v-model="content.startTime" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间">
                <el-input v-model="content.endTime" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="行程详情">
            <el-input v-model="content.scheduleContent" type="textarea" rows="2" disabled />
          </el-form-item>

          <!-- 图片展示（如果有） -->
          <el-form-item label="行程图片" v-if="content.picture1 || content.picture2 || content.picture3">
            <el-row :gutter="10">
              <el-col :span="7" v-if="content.picture1">
                <img :src="content.picture1" class="content-img" alt="行程图片1">
              </el-col>
              <el-col :span="8" v-if="content.picture2">
                <img :src="content.picture2" class="content-img" alt="行程图片2">
              </el-col>
              <el-col :span="7" v-if="content.picture3">
                <img :src="content.picture3" class="content-img" alt="行程图片3">
              </el-col>
            </el-row>
          </el-form-item>

          <el-row :gutter="15" class="mb8">
            <el-col :span="12">
              <el-form-item label="旅行费用">
                <el-input v-model="content.travelMoney" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务费用">
                <el-input v-model="content.serviceMoney" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="费用说明" v-if="content.remark">
            <el-input v-model="content.remark" type="textarea" rows="2" disabled />
          </el-form-item>

          <hr v-if="index !== dialogForm.scheduleContents.length - 1">
        </div>
      </div>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit" v-if="!isDetailMode">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 引入获取行程详情和内容的API（路径根据实际项目调整）
import { getScheduleDetail } from '@/api/travel/schedule';
import { getContent } from '@/api/travel/schedule/content';

export default {
  name: 'ScheduleDetailDialog',
  props: {
    // 控制对话框显示/隐藏
    visible: {
      type: Boolean,
      default: false
    },
    // 行程ID（用于加载详情）
    scheduleId: {
      type: [Number, String],
      required: true // 必须传递行程ID
    },
    // 是否为详情模式（只读）
    isDetailMode: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 加载状态
      loading: false,
      // 表单数据（完整初始化，避免undefined）
      dialogForm: {
        scheduleId: null,
        travelMoneyTotal: null,
        serviceMoneyTotal: null,
        moneyTotal: null,
        travelConsult: {
          consultNumber: null,
          travelerCount: null,
          preferredDestination: null,
          budget: null,
          estimatedTime: null,
          flexibleDays: null,
          plannedDays: null,
          remark: null
        },
        travelClient: {
          clientName: null,
          clientTel: null
        },
        // 行程内容列表（初始为空数组，确保循环不报错）
        scheduleContents: []
      },
      // 表单验证规则（根据需要添加）
      rules: {}
    };
  },
  computed: {
    // 对话框标题
    dialogTitle() {
      return this.isDetailMode ? '行程详情' : '编辑行程';
    }
  },
  watch: {
    // 当对话框显示且行程ID存在时，加载数据
    visible(newVal) {
      if (newVal && this.scheduleId) {
        this.loadScheduleDetail();
      }
    },
    // 行程ID变化时，重新加载数据
    scheduleId(newVal) {
      if (this.visible && newVal) {
        this.loadScheduleDetail();
      }
    }
  },
  methods: {
    // 加载行程详情（核心：获取完整数据，包括行程内容）
    async loadScheduleDetail() {
      if (!this.scheduleId) return;

      this.loading = true;
      try {
        // 1. 获取行程主信息
        const scheduleRes = await getScheduleDetail(this.scheduleId);
        const scheduleData = scheduleRes.data || {};

        // 2. 获取行程内容列表
        const contentRes = await getContent(this.scheduleId);
        const contentList = contentRes.data || [];

        // 3. 填充表单数据（确保所有嵌套字段都有值）
        this.dialogForm = {
          ...scheduleData,
          travelConsult: scheduleData.travelConsult || this.dialogForm.travelConsult,
          travelClient: scheduleData.travelClient || this.dialogForm.travelClient,
          // 关键：填充行程内容列表
          scheduleContents: contentList
        };

      } catch (error) {
        console.error('加载行程详情失败:', error);
        this.$message.error('加载失败，请重试');
        this.dialogForm.scheduleContents = []; // 出错时重置为空数组
      } finally {
        this.loading = false;
      }
    },
    // 关闭对话框
    handleClose() {
      this.$emit('update:visible', false);
      // 重置数据（避免下次打开显示旧数据）
      this.resetForm();
    },
    // 重置表单
    resetForm() {
      this.dialogForm = {
        scheduleId: null,
        travelMoneyTotal: null,
        serviceMoneyTotal: null,
        moneyTotal: null,
        travelConsult: {
          consultNumber: null,
          travelerCount: null,
          preferredDestination: null,
          budget: null,
          estimatedTime: null,
          flexibleDays: null,
          plannedDays: null,
          remark: null
        },
        travelClient: {
          clientName: null,
          clientTel: null
        },
        scheduleContents: []
      };
    },
    // 提交（仅编辑模式用，详情模式隐藏）
    handleSubmit() {
      this.$emit('submit', this.dialogForm);
      this.handleClose();
    }
  }
};
</script>

<style scoped>
/* 确保行程内容区域样式正确，不被隐藏 */
.dynamic-schedule-content {
  margin-top: 20px;
  overflow-y: auto;
  max-height: 500px;
  /* 根据需要调整最大高度 */
  padding-right: 10px;
}

.step-content {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  background-color: #fff;
}

/* 图片样式 */
.content-img {
  width: 100%;
  max-width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

/* 无数据提示样式 */
.no-content {
  text-align: center;
  padding: 30px;
  color: #999;
  background-color: #f5f5f5;
  border-radius: 4px;
}

/* 费用区域样式 */
.total-fee-container {
  margin: 20px 0;
  padding: 10px 0;
}

/* 加载状态样式 */
.loading-container {
  min-height: 400px;
  /* 避免加载时对话框高度闪烁 */
}
</style>
